#include "pwm.h"
#include "stm32f4xx_tim.h"

//16A 289 26.7%
//32A 555 53.3%
//1000范围内，设置的值/100即为占空比
//千分比 600/1000 为 60% 高电平
void pwm_init(int pulse)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    TIM_TimeBaseInitTypeDef  TIM_BaseInitStructure;

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4,ENABLE); 
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); 	

    GPIO_PinAFConfig(GPIOB, GPIO_PinSource8, GPIO_AF_TIM4);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;       
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;       
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;	
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;      
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;      
    GPIO_Init(GPIOB,&GPIO_InitStructure);             


    TIM_DeInit(TIM4);
    TIM_InternalClockConfig(TIM4);
    TIM_BaseInitStructure.TIM_Period = 987;

    TIM_BaseInitStructure.TIM_Prescaler = 84;

    TIM_BaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_BaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;

    TIM_TimeBaseInit(TIM4, &TIM_BaseInitStructure);
    TIM_ARRPreloadConfig(TIM4, ENABLE);
    TIM_Cmd(TIM4, ENABLE);

    TIM_OCInitTypeDef  TIM_OCInitStructure;
    TIM_OCStructInit(&TIM_OCInitStructure);
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStructure.TIM_Pulse = pulse;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;

    TIM_OC3Init(TIM4, &TIM_OCInitStructure);
    TIM_OC3PreloadConfig(TIM4, TIM_OCPreload_Enable);
    TIM_CtrlPWMOutputs(TIM4, ENABLE);
}

void pwm_on(void){  
    TIM_Cmd(TIM4, ENABLE); 
}

void pwm_off(void){
    TIM_GenerateEvent(TIM4,TIM_EventSource_Update);
    TIM_Cmd(TIM4, DISABLE); 
}
